package com.sxx.beautifulcity.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.sxx.beautifulcity.R;
import com.sxx.beautifulcity.activity.NearFragmentDetailActivity;
import com.sxx.beautifulcity.adapter.NearRecyclerViewAdapter;
import com.sxx.beautifulcity.entity.DeliciousFoodData;
import com.sxx.beautifulcity.entity.PetData;
import com.sxx.beautifulcity.entity.Poi_List;
import com.sxx.beautifulcity.entity.SpecialityData;
import com.sxx.beautifulcity.entity.Tuan_list_NearPayAtshopData;
import com.sxx.beautifulcity.entity.Tuan_list_ResultData;
import com.sxx.beautifulcity.entity.Tuan_list_Tongyong;
import com.sxx.beautifulcity.entity.Tuan_list_WifiData;
import com.sxx.beautifulcity.entity.greendao.AgritourismDaoEntity;
import com.sxx.beautifulcity.entity.greendao.AroundDaoEntity;
import com.sxx.beautifulcity.entity.greendao.HolidayDaoEntity;
import com.sxx.beautifulcity.entity.greendao.PluckDaoEntity;
import com.sxx.beautifulcity.entity.greendao.VillageDaoEntity;
import com.sxx.beautifulcity.listenerInterface.OnMyItemClickListener;
import com.sxx.beautifulcity.constant.Constant;
import com.sxx.beautifulcity.utils.VolleySingleton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/23.
 */
public class NearFragment extends Fragment implements OnMyItemClickListener {

    private final static String TAG = "NearFragment";
    private NearRecyclerViewAdapter adapter;
    private RecyclerView recyclerView_near;
    private GridLayoutManager manager;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }


    /*****
     * 加载布局
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.recyclerview_near, container, false);
        return v;
    }

    /****
     * 初始化控件
     *
     * @param view
     * @param savedInstanceState
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView_near = (RecyclerView) view.findViewById(R.id.recyclerView_near);
    }

    /***
     * 写逻辑
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        requestContent();
        adapter = new NearRecyclerViewAdapter();
        manager = new GridLayoutManager(getActivity(), 1);
        recyclerView_near.setLayoutManager(manager);
        recyclerView_near.setAdapter(adapter);
        adapter.setOnMyItemClickListener(this);
    }

    public void requestContent() {
        //final CommonProgressDialog dialog = new CommonProgressDialog(getContext(), "正在加载中.......", R.anim.main_anim);
        //dialog.show();

        String path = Constant.NAER_SPEC_URL;
        JsonObjectRequest request = new JsonObjectRequest(path, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        if (response != null && response.has("data")) {
                            try {
                                Gson gson = new Gson();
                                List<Poi_List> poiLists = new ArrayList<>();
                                List<Tuan_list_ResultData> listResult = new ArrayList<>();
                                List<Tuan_list_NearPayAtshopData> listShopData = new ArrayList<>();
                                List<Tuan_list_Tongyong> list_tongyongs = new ArrayList<>();
                                List<Tuan_list_WifiData> listWifiDatas = new ArrayList<>();
                                JSONObject object = response.getJSONObject("data");
                                if (object.has("poi_list")) {
                                    JSONArray array = object.getJSONArray("poi_list");
                                    for (int i = 0; i < array.length(); i++) {
                                        JSONObject object1 = array.getJSONObject(i);

                                        if (object1.has("tuan_list")) {
                                            JSONArray tuan_list = object1.getJSONArray("tuan_list");
                                            for (int k = 0; k < tuan_list.length(); k++) {
                                                JSONObject jsonObject = tuan_list.getJSONObject(k);
                                                String str3 = tuan_list.getString(k);
                                                Tuan_list_Tongyong listTongyong = gson.fromJson(str3, Tuan_list_Tongyong.class);
                                                list_tongyongs.add(listTongyong);
                                            }
                                        }
                                        if (object1.has("payAtshop")) {
                                            JSONObject object2 = object1.getJSONObject("payAtshop");
                                            String str2 = object2.toString();
                                            Tuan_list_NearPayAtshopData atshopData = gson.fromJson(str2, Tuan_list_NearPayAtshopData.class);
                                            listShopData.add(atshopData);
                                        }

                                        String str = array.getString(i);
                                        Tuan_list_ResultData resultData = gson.fromJson(str, Tuan_list_ResultData.class);
                                        listResult.add(resultData);
                                    }

                                }
                                adapter.addData(listResult, listShopData, list_tongyongs);
                                //dialog.dismiss();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }) {
            //添加请求头
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }

            //解决解析后程序乱码问题
            @Override
            protected Response<JSONObject> parseNetworkResponse(
                    NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(new JSONObject(jsonString),
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }
        };
        VolleySingleton.getInstance().addRequest(request, TAG);
    }

    @Override
    public void onMyItemClick(Tuan_list_Tongyong data) {

        Intent intent = new Intent(getActivity(), NearFragmentDetailActivity.class);
        intent.putExtra("user_distance_poi", data.getUser_distance_poi());
        startActivity(intent);
        getActivity().finish();
        Log.i("jdjgjfd", data.getUser_distance_poi() + "");
    }

    @Override
    public void onMyItemClick(AroundDaoEntity lineData) {

    }

    @Override
    public void onMyItemClick(HolidayDaoEntity data) {

    }

    @Override
    public void onMyItemClick(AgritourismDaoEntity data) {

    }

    @Override
    public void onMyItemClick(PluckDaoEntity data) {

    }

    @Override
    public void onMyItemClick(VillageDaoEntity data) {

    }


    @Override
    public void onMyItemClick(SpecialityData data) {

    }

    @Override
    public void onMyItemClick(DeliciousFoodData data) {

    }

    @Override
    public void onMyItemClick(PetData data) {

    }

}
